package zsh.aop;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;
import zsh.domain.Student;
import zsh.domain.User;

@Aspect
@Component
public class WorkAspect {
    @Pointcut("execution(* zsh.service.IUserService.add*(..)) || " +
            "execution(* zsh.service.IStudentService.add*(..))")
    public void addMethodPointcut() {}

    // 前置通知：方法执行前记录日志
    @Before("addMethodPointcut()")
    public void logBeforeAdd(JoinPoint joinPoint) {
        Object[] args = joinPoint.getArgs();
        for (Object arg : args) {
            if (arg instanceof User) {
                System.out.println("执行了新增用户操作: " +"参数是"+ arg);
            } else if (arg instanceof Student) {
                System.out.println("执行了新增学生操作: " +"参数是"+ arg);
            }
        }
    }

    // 获取返回值通知：方法成功执行后记录日志
    @AfterReturning(pointcut = "addMethodPointcut()")
    public void logAfterSuccess(JoinPoint joinPoint) {
        System.out.println("成功添加: " +"执行的方法是"+ joinPoint.getSignature().getName());
    }

    // 异常通知：方法抛出异常后记录日志
    @AfterThrowing(pointcut = "addMethodPointcut()", throwing = "exception")
    public void logAfterFailure(JoinPoint joinPoint, Throwable exception) {
        System.out.println("出现异常: " +"出现异常的方法是"+ joinPoint.getSignature().getName() +
                "异常是: " + exception.getMessage());
    }
    //后置通知：总之就是执行了
    @After("addMethodPointcut()")
    public void logAfter(JoinPoint joinPoint) {
        System.out.println("执行的类是:"+joinPoint.getSignature().getDeclaringType().getSimpleName());
        System.out.println("不管成功还是失败总之是执行完了");
    }
}